from email import parser, policy


def http_parse(http_pkg):
    """
    http报文初步解析函数
    参数：http报文字符串
    返回：http起始行，headers, body
    """
    ENTER = "\n"
    CLRF = "\r\n"
    if ENTER in http_pkg:    # 处理非CLRF分割的http报文
        res = http_pkg_split(ENTER, http_pkg)
    elif CLRF in http_pkg:
        res = http_pkg_split(CLRF, http_pkg)

    return res


def http_pkg_split(sep, http_pkg):
    """
    http报文分割函数
    参数：http报文字符串，分割字符
    返回：http起始行，headers, body
    """
    tmp = http_pkg.split(sep=sep, maxsplit=1)

    start_line = tmp[0]

    others = tmp[1]     # 去除http报文起始行之后，剩余的内容应完全遵从MIME数据格式
    # 指定policy为HTTP，使得遵循 RFC 2822以及当前的各种 MIME RFC（RFC 5322, RFC 2047)
    p = parser.Parser(policy=policy.HTTP)
    msg = p.parsestr(text=others, headersonly=False)   # 解析header和body

    headers = {}
    for k, v in msg.items():
        headers[k] = str(v)

    body = msg.get_payload()

    return start_line, headers, body
